<template>
  <div>
    <!--一口价询运费-->
    <el-dialog
      :close-on-click-modal="false"
      title="询运费"
      :visible.sync="dialogVisible"
      :beforeClose="handleClose"
      width="800px"
    >
      <div>
        <el-form
          :model="sendForm"
          size="mini"
          label-width="100px"
          ref="sendForm"
          :rules="rules"
        >
          <el-form-item label="客户名称：" prop="customerName">
            <el-select
              clearable
              v-model="sendForm.customerName"
              filterable
              remote
              @change="changeReceiveAreaId"
              reserve-keyword
              placeholder="请输入关键词"
              :remote-method="querySearch"
            >
              <el-option
                v-for="item in querySearchList"
                :key="item.customerId"
                :label="item.customerName"
                :value="item"
              >
              </el-option>
            </el-select>
            <div style="padding-left:15px;color:red;font-size: 12px" v-if="isEnableOrder === 0">注意:该客户最近1年存在降价违约{{ defaultNum }}次,超期未清款{{outTimeUnPaidAmount}}元，限制询盘和下单!</div>
            <!-- <el-button type="text" style="margin-left:5px" @click="showPop8">新增客户</el-button> -->
          </el-form-item>
          <el-form-item label="收货地址：" prop="receiveAreaId">
            <el-cascader
              filterable
              clearable
              v-model="sendForm.receiveAreaId"
              :props="{
                value: 'areaId',
                label: 'areaName',
                children: 'children',
              }"
              :options="options"
            ></el-cascader>
            <!-- <el-button type="text" style="margin-left:5px" @click="showPop8">管理地址</el-button> -->
          </el-form-item>
          <el-form-item  label="订单分类：" prop="saleCustomerType">
            <el-select v-model="sendForm.saleCustomerType" filterable clearable>
              <el-option
                v-for="(item,index) in orderCustomerTypeList"
                :key="index"
                :label="item.cddValue"
                :value="item.cddValue">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="业务员:" v-if="inquiryUserList.length==1">
            {{ inquiryUserList[0].userName }}
          </el-form-item>
          <el-form-item label="业务员:" prop="inquiryUserId" v-if="inquiryUserList.length>1">
            <el-select
              v-model="sendForm.inquiryUserId"
              clearable
              filterable
            >
              <el-option
                v-for="item in inquiryUserList"
                :key="item.userId"
                :value="item.userId"
                :label="item.userName"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-table
            :data="sendForm.goodsList"
            size="mini"
            :header-cell-style="{ background: '#f8f8f9', color: '#80878f' }"
            border
            style="width: 100%; margin-top: 20px"
          >
            <!-- <el-table-column
            width="180"
            label="供货方"
            align="center">
            <template slot-scope="scope">
              {{ scope.row.fromCompany }}
            </template>
          </el-table-column> -->
            <el-table-column width="180" label="品名牌号" align="center">
              <template slot-scope="scope">
                {{ scope.row.categoryName }}/{{ scope.row.goodsSn }}
              </template>
            </el-table-column>

            <!-- <el-table-column
            label="收货方式"
            align="center">
            <template slot-scope="scope">
              {{scope.row.sendTypes}}
            </template>
          </el-table-column> -->
            <!-- <el-table-column
            label="期望收货时间"
            align="center">
            <template slot-scope="scope">
              {{scope.row.createdTime}}
            </template>
          </el-table-column> -->
            <el-table-column label="发货地区" min-width="200" align="center">
              <template slot-scope="scope">
                {{ scope.row.sendArea }}
              </template>
            </el-table-column>
            <!-- <el-table-column
            label="发货日期"
            align="center">
            <template slot-scope="scope">
              {{scope.row.sendDate}}
            </template>
          </el-table-column> -->
            <el-table-column label="采购底价" width="180" align="center">
              <template slot-scope="scope">
                {{ scope.row.purchasePrice }}
              </template>
            </el-table-column>
            <el-table-column label="数量" width="150" align="center">
              <template slot-scope="scope">
                <el-form-item
                  style="margin-bottom: 0"
                  :prop="`goodsList.${scope.$index}.goodsNum`"
                  :rules="rules.goodsNum"
                  label-width="0px"
                >
                  <el-input
                    v-model="scope.row.goodsNum"
                    type="number"
                    size="mini"
                  ></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="物流备注" min-width="180" align="center">
              <template slot-scope="scope">
                <el-form-item label-width="0px" style="margin-bottom: 0px">
                  <el-input
                    placeholder="物流备注：如加托"
                    v-model="scope.row.freightRemark"
                    clearable
                  ></el-input>
                </el-form-item>
              </template>
            </el-table-column>
          </el-table>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="handleConfirm" :loading="btnLoading" :disabled="isEnableOrder === 0"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <!--新增客户-->
    <!-- <addCustomer ref="addCustomer"></addCustomer> -->
  </div>
</template>
<script>
import {
  getCustomerList,
  getAreaList,
  fixedPriceFreight,
  goodsPriceListInfo,
  getSaleUserListAPI
} from "@/api/allInLine/inquiry";
// import addCustomer from "./addCustomer";
import {getCustomerDefaultNum} from "@/api/order";
import {getConfigList} from '@/api/partner';
import { mapGetters } from "vuex";
import { Message } from "element-ui";
const defaultSendForm = {
  companyId: "",
  customerName: "",
  receiveAreaId: "",
  inquiryUserId:"",
  goodsList: [],
  freightRemark: "",
  saleCustomerType:''
};
export default {
  name: "index",
  data() {
    const validateNumber = (rule, value, callback) => {
      if (!value) {
        Message.error("下单数量必填");
        callback(new Error("下单数量必填"));
      } else if (value > 9999 || value < 0) {
        Message.error("数量为0-9999");
        callback(new Error("数量为0-9999"));
      } else {
        callback();
      }
    };
    return {
      inquiryUserList:[],
      inquiryId: "",
      priceIds: "",
      applyIds: "",
      dialogVisible: false,
      btnLoading: false,
      sendForm: JSON.parse(JSON.stringify(defaultSendForm)),
      type: "",
      rules: {
        goodsNum: [
          { required: true, validator: validateNumber, trigger: "blur" },
        ],
        customerName: [
          { required: true, message: "请选择客户名称", trigger: "change" },
        ],
        inquiryUserId: [
          {required: true, message: "请选择业务员", trigger: "change"}
        ],
        receiveAreaId: [
          { required: true, message: "请选择收货地址", trigger: "change" },
        ],
        saleCustomerType:[
          { required: true, message: "请选择订单分类", trigger: "change" },
        ],
      },

      options: [],
      querySearchList: [],
      diQuIds: [],

      defaultNum:0,
      isEnableOrder:'',
      outTimeUnPaidAmount:0,
      orderCustomerTypeList:[]
    };
  },
  computed: {
    ...mapGetters(["name", "mobile", "userId"]),
  },
  components: {
    // addCustomer,
  },
  created() {
    // this.getSaleUserList()
  },
  filters: {},
  methods: {
    //获取订单分类列表
    getOrderCustomerType(){
      getConfigList({status:1}).then((res)=>{
        let orderCustomerType = res.find((el)=>{
          return  el.cdtCode == 'order_customer_type'
        })
        this.orderCustomerTypeList = orderCustomerType ? orderCustomerType.data : []
      })
    },
    //获取省市区列表
    getAddressListData() {
      getAreaList().then((res) => {
        this.options = res;
      });
    },
    // showPop8() {
    //   this.$refs.addCustomer.showPop8();
    // },
    //客户名称输入匹配
    querySearch(queryString, tab) {
      if (queryString && queryString != "") {
        if (tab == "all") {
          getCustomerList({ keywords: queryString, tab: "all" }).then((res) => {
            this.querySearchList = res;
            // const provinceId = res[0].provinceId ? res[0].provinceId : "";
            // const cityId = res[0].cityId ? res[0].cityId : "";
            // const areaId = res[0].areaId ? res[0].areaId : "";
            // this.sendForm.receiveAreaId = provinceId ? [provinceId, cityId, areaId] : [];
            // console.log(this.sendForm.receiveAreaId)
          });
        } else {
          getCustomerList({ keywords: queryString, tab: "my" }).then((res) => {
            this.querySearchList = res;
            // const provinceId = res[0].provinceId ? res[0].provinceId : "";
            // const cityId = res[0].cityId ? res[0].cityId : "";
            // const areaId = res[0].areaId ? res[0].areaId : "";
            // this.sendForm.receiveAreaId = provinceId ? [provinceId, cityId, areaId] : [];
            // console.log(this.sendForm.receiveAreaId)
          });
        }
      }
    },
    changeReceiveAreaId(val) {
      this.sendForm.companyId = val.customerId == 0 ? "" : val.customerId;
      this.sendForm.customerName =val.customerName == 0 ? "" : val.customerName;
      this.sendForm.receiveAreaId = val.provinceId ? [val.provinceId, val.cityId, val.areaId] : [];
      this.getCustomerWy()
      // this.getSaleUserList()
    },
    getCustomerWy(){
      this.defaultNum = 0
      if(this.sendForm.companyId){
        getCustomerDefaultNum({customerId:this.sendForm.companyId}).then((res)=>{
          this.defaultNum = res.defaultNum
          this.isEnableOrder = res.isEnableOrder
          this.outTimeUnPaidAmount = res.outTimeUnPaidAmount
        })
      }
    },
    // 获取业务员列表
    getSaleUserList() {
      getSaleUserListAPI({
        type:"inquiry"
      }).then((res) => {
        this.inquiryUserList = res;
        if (this.inquiryUserList.length == 1) {
          this.sendForm.inquiryUserId=this.inquiryUserList[0].userId
        }
      }).catch((error) => {
        console.log(error);
      })
    },
    //显示询运费
    showPop(goodsData, type) {
      this.type = type;
      this.sendForm = JSON.parse(JSON.stringify(defaultSendForm));
      this.dialogVisible = true;
      this.getAddressListData();
      this.getSaleUserList()
      this.getOrderCustomerType();
      if (type == "oneprice") {
        const onePriceNum = goodsData.map((item) => item.priceId);
        this.priceIds = onePriceNum.join(",");
      } else if (type == "lockGoods") {
        this.applyIds = goodsData.applyId;
      }
      goodsPriceListInfo({
        priceIds: this.priceIds,
        applyIds: this.applyIds,
      }).then((res) => {
        this.querySearch(res[0].customerName, "all");
        this.sendForm.companyId =
          res[0].customerId == 0 ? "" : res[0].customerId;
        this.sendForm.customerName =
          res[0].customerName == 0 ? "" : res[0].customerName;

        res.forEach((item) => {
          this.sendForm.goodsList.push(item);
        });
        this.getCustomerWy()
      });
    },
    //关闭询运费
    handleClose() {
      this.dialogVisible = false;
      this.$refs.sendForm.resetFields();
      // this.sendForm = JSON.parse(JSON.stringify(defaultSendForm));
    },

    //确认询运费
    handleConfirm() {
      this.$refs.sendForm.validate((valid) => {
        // let goodsList = [];
        if (valid) {
          this.btnLoading = true;
          let goodsList = [];
          this.sendForm.goodsList.forEach((item) => {
            if (this.type == "oneprice") {
              goodsList.push({
                priceId: item.priceId,
                goodsNum: item.goodsNum,
                freightRemark: item.freightRemark,
              });
            } else {
              goodsList.push({
                applyId: item.applyId,
                goodsNum: item.goodsNum,
                freightRemark: item.freightRemark,
              });
            }
          });
          // const receiveSendAreaId = this.sendForm.receiveAreaId
          //   ? this.sendForm.receiveAreaId[
          //       this.sendForm.receiveAreaId.length - 1
          //     ]
          //   : "";
          // const data = {
          //   companyId: this.sendForm.companyId,
          //   receiveAreaId: receiveSendAreaId,
          //   goodsList,
          // };
          const data = JSON.parse(JSON.stringify(this.sendForm))
          data.receiveAreaId=this.sendForm.receiveAreaId[2]
          fixedPriceFreight(data)
            .then((res) => {
              Message.success("确认成功");
              this.btnLoading = false;
              // this.sendForm = JSON.parse(JSON.stringify(defaultSendForm));
              this.$emit("update");
              this.dialogVisible = false;
            })
            .catch((error) => {
              this.btnLoading = false;
            });
        }
      });
    },
  },
};
</script>

<style  lang="scss">
</style>
